package com.wc.week3.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wc.week3.entity.Goods;
import com.wc.week3.service.GoodsService;
import com.wc.week3.vo.GoodsVo;
import org.springboot.bw.struct.PageResult;
import org.springboot.bw.struct.Result;
import org.springboot.bw.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 关注公众号：王聪
 * @since 2022-07-06
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Resource
    GoodsService goodsService;

    @PostMapping("/search/{cp}/{pageSize}")
    public PageResult<Goods> search(@PathVariable("cp")Integer cp,
                                    @PathVariable("pageSize")Integer pageSize,
                                    @RequestBody(required = false)GoodsVo vo){
        QueryWrapper<Goods> qw = new QueryWrapper<>();
        if(Objects.nonNull(vo)){
            if(StringUtils.isNotEmpty(vo.getGoodsName())){
                qw.like("goodsName",vo.getGoodsName());
            }
            if(StringUtils.isNotEmpty(vo.getProductName())){
                qw.like("productName",vo.getProductName());
            }
        }

        Page<Goods> objectPage = new Page<>(cp,pageSize);
        Page<Goods> page = goodsService.page(objectPage, qw);
        PageResult<Goods> of = PageResult.of(page.getRecords(), page.getTotal());
        return of;

    }

    @PostMapping("/add")
    public Result add(@RequestBody Goods goods){
        boolean save = goodsService.save(goods);
        return save==true?Result.ok():Result.error();
    }

    @PutMapping("/update")
    public Result update(@RequestBody Goods goods){
        Goods byId = goodsService.getById(goods.getId());
        byId.setGoodsName(goods.getGoodsName());
        byId.setPrice(goods.getPrice());
        byId.setGoodsDate(goods.getGoodsDate());
        byId.setPiHao(goods.getPiHao());
        byId.setProductName(goods.getProductName());

        boolean b = goodsService.updateById(byId);
        return b==true?Result.ok():Result.error();
    }

    @DeleteMapping("/delete/{id}")
    public Result update(@PathVariable("id")Integer id){
        boolean b = goodsService.removeById(id);
        return b==true?Result.ok():Result.error();
    }

}
